package uk.ac.bbk.dcs.muc;

/**
 * Copyright [2011] [Sean Howes and Aruna Gunasekera]
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class EventSqlLiteHelper extends SQLiteOpenHelper {
	
	public static final String DB_NAME  = "event_db.sqlite";
	public static final String EVENT_TABLE  = "event";
	// Column names
	public static final String EVENT_ID = "id";
	public static final String EVENT_NAME = "type";
	public static final String EVENT_TIME = "timestamp";
	public static final String EVENT_DATA  = "details";
	// Column numbers 
	public static final int TIME_STAMP_COL_NO = 1;
	public static final int NAME_COL_NO = 2;
	public static final int DATA_COLUMN_NO = 3;
	
	public EventSqlLiteHelper(Context context) {
		super(context, DB_NAME, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		dropAndCreate(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	protected void dropAndCreate(SQLiteDatabase db) {
		db.execSQL("drop table if exists " + EVENT_TABLE + ";");
		createTables(db);
	}
	
	/***
	 * Create inital event db
	 * @param db
	 */
	protected void createTables(SQLiteDatabase db) {
		try {
		db.execSQL(
				"create table " + EVENT_TABLE +" (" +
				EVENT_ID + " integer primary key autoincrement not null," +
				EVENT_TIME + " text," +
				EVENT_NAME + " text," +
				EVENT_DATA + " text" +
				");"
			);
		} catch (Exception e) {
			Log.e("sqlError",e.getMessage());
		}
	}
	
	/***
	 * Write a event record to the database
	 * @param name
	 * @param timeStamp
	 * @param value
	 * @param database
	 * @return
	 */
	public static long writeRecordToDb(String name,Long timeStamp, String value,SQLiteDatabase database) {
		ContentValues values = new ContentValues();
		values.put(EVENT_NAME, name);
		values.put(EVENT_TIME, timeStamp);
		values.put(EVENT_DATA, value);
		return database.insert(EVENT_TABLE, null, values);
	}

}
